<template>
  <Layout>
    <Spin fix v-if="isSpin">
      <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
      <div>正在导出环境保护税统计表，请稍后</div>
    </Spin>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row :gutter="16" class="query-form2" v-show="!switchFlag">
        <Col span="8">
          <FormItem label="单位名称：" prop="receiptOrgName">
            <cascaderDom class="query-form-el" style="padding-top: 4px;width: 100%"
                         @setOrgInfo="setOrgId1" @setOrgname="setOrgName1" ref="org1"
                         :currentOrgId="form1.companyId"
                         :currentOrgName="form1.companyName" :orgTree="true"></cascaderDom>
          </FormItem>
        </Col>
        <Col span="8">

        </Col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
<!--            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">-->
<!--              展开-->
<!--              <Icon type="ios-arrow-down"/>-->
<!--            </Button>-->
          </div>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">

        <Col span="8" offset="16">
          <div style="float: right;height:44px">
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2"
                    type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="loading" @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :title="add?'环境保护税统计表新增':'环境保护税统计表修改'" :transfer=false v-model="model1" :width=1200>
      <Row>
        <Col span="24">
          <Form ref="form1datacopy1" :model="form1datacopy" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="单位名称：" prop="companyId">
                  <!--                  <cascaderDom class="query-form-el" style="padding-top: 4px;width: 100%"-->
                  <!--                               ref="company"-->
                  <!--                               @setOrgInfo="setOrgId" @setOrgname="setOrgName"-->
                  <!--                               :currentOrgId="form1datacopy.companyId"-->
                  <!--                               :currentOrgName="form1datacopy.companyName"-->
                  <!--                               :orgTree="true"></cascaderDom>-->
                  <Input type="text" v-model="form1datacopy.companyName" readonly></Input>
                </FormItem>

              </Col>
              <Col span="11">
                <FormItem label="所属二级集团：" >
                  <Input type="text" v-model="form1datacopy.twoOrgName" readonly></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="税期：" prop="taxPeriod">
                  <DatePicker type="daterange" v-model="form1datacopy.taxPeriod" split-panels placeholder="请选择"
                              style="width: 100%"></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填表日期：" prop="fillDate">
                  <DatePicker type="date" v-model="form1datacopy.fillDate" placeholder="请选择"
                              style="width:  100%"></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Form>
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="23">
              <Button style="margin-top:20px" class="ivu-btn-add" icon="md-add" @click="addPlan()">新增
              </Button>
            </Col>
          </Row>
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="23">
              <Table class="tableClass" border stripe style="margin-top:20px;overflow-y:auto;" size="small"
                     :height="350" :loading="loading" :columns="planColumn" :data="form1datacopy.items">
              </Table>
            </Col>
          </Row>

        </Col>
      </Row>
      <div slot="footer">
        <Button @click="submit('form1datacopy1')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
    <Modal title="环境保护税统计表详情" :transfer=false v-model="model2" :width=1200 class="modal-view-detail">
      <Row>
        <Col span="24">
          <Form :model="form1datacopy" :label-width="100">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="单位名称：" >
                  {{ form1datacopy.companyName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="二级集团：" >
                  {{ form1datacopy.twoOrgName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="税期：" >
                  {{formDataTwo(form1datacopy.taxPeriodStart,form1datacopy.taxPeriodEnd)}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填表日期：" >
                  {{ formData(form1datacopy.fillDate) }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <Table  border stripe style="margin-top:20px;overflow-y:auto;" size="small"
                       :height="350" :loading="loading" :columns="planColumnView" :data="form1datacopy.items">
                </Table>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>

    <Modal title="批量新增" :transfer=false v-model="model10" :width=900>
      <div style="height: 400px; overflow-y: auto; overflow-x: auto;">
        <Tree ref="auditTree" show-checkbox multiple :data="orderTreeHead"></Tree>
      </div>
      <div slot="footer">
        <Button @click="addSelectplanData()" class="ivu-btn-save" :loading="buttonLoading10">确定</Button>
        <Button @click="addHandleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
  </layout>
</template>

<script>
import {Api} from '../../../api/index.js'
import {sessionStorage} from '../../../common/cacheUtils.js';

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components: {cascaderDom},
  data() {
    return {
      treeListFilter: {},
      orderTreeHead: [
        {
          id: 1,
          loading: false,
          title: '隐患条目',
          expand: false,
          children: []
        }
      ],
      buttonLoading10: false,
      model10: false,
      currentUser: sessionStorage('userId').getObject('userId'),
      buttonLoading: false,
      uploadList: [],
      queryMeetingSelectModal: false,
      loading: false,
      activityForSelectModal: false,
      switchFlag: false,
      form1: {},
      fileUrl: Api.interestedPartiesUserFile,
      standardSelectModal: false,
      //分页参数
      receiptDate: ['', ''],
      pageSizeArray: [10, 20, 50],
      isSpin: false,
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },

        {
          minWidth: 200,
          title: '所属二级集团',
          align: 'center',
          key: 'twoOrgName',
        },
        {
          minWidth: 200,
          title: '所属公司',
          align: 'center',
          key: 'companyName',
        },
        {
          minWidth: 300,
          title: '税期',
          align: 'center',
          key: 'taxPeriod',
          render: (h, params) => {
            let _this  = this;
            if (params.row["taxPeriodStart"] && params.row["taxPeriodEnd"]) {
              params.row.taxPeriod = _this.formatDate(new Date(params.row["taxPeriodStart"]), "yyyy-MM-dd") + "~" + _this.formatDate(new Date(params.row["taxPeriodEnd"]), "yyyy-MM-dd");
              return h('span', params.row.taxPeriod);
            } else {
              return h('span', "--");
            }
          }
        },
        {
          minWidth: 100,
          title: '填表日期',
          align: 'center',
          key: 'fillDate',
          render: (h, params) => {
            if (params.row["fillDate"]) {
              return h('span', this.formatDate(new Date(params.row["fillDate"]), "yyyy-MM-dd"));
            } else {
              return h('span', "--");
            }

          }
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
            if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                    ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.downloadFiles(params.row.id);
                    }
                  }
                }, '导出'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 2);
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: 'red'},
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '数据删除',
                        content: '<p>确定删除该条信息</p>',
                        okText: '确认',
                        onOk: () => {
                          this.deleteData(params);
                        },
                        cancelText: '取消'
                      });
                    }
                  }
                }, '删除')
              ]);
            } else {

              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.downloadFiles(params.row.id);
                    }
                  }
                }, '导出'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }

          }
        }
      ],
      ruleCustom: {
        companyId: [{
          validator: (rule, value, callback) => {
            if (!this.form1datacopy.companyId) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        twoLevelOrgId: [{
          validator: (rule, value, callback) => {
            if (!this.form1datacopy.twoLevelOrgId) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        fillDate: [{
          validator: (rule, value, callback) => {
            if (!this.form1datacopy.fillDate) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        taxPeriod: [{
          validator: (rule, value, callback) => {
            if (!this.form1datacopy.taxPeriod[0] && !this.form1datacopy.taxPeriod[1]) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        receiptDate: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.receiptDate == null || this.form1datacopy.receiptDate == '' || this.form1datacopy.receiptDate == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      ruleCustomModify: {
        informId: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.informId == null || this.form1datacopy.informId == '' || this.form1datacopy.informId == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.form1datacopy.phone))) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        receiptOrgId: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.receiptOrgId == null || this.form1datacopy.receiptOrgId == '' || this.form1datacopy.receiptOrgId == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        contactName: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.contactName == null || this.form1datacopy.contactName == '' || this.form1datacopy.contactName == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        receiptDate: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.receiptDate == null || this.form1datacopy.receiptDate == '' || this.form1datacopy.receiptDate == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        userName: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.userName == null || this.form1datacopy.userName == '' || this.form1datacopy.userName == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        position: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.position == null || this.form1datacopy.position == '' || this.form1datacopy.position == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        depName: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.depName == null || this.form1datacopy.depName == '' || this.form1datacopy.depName == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        cellPhone: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.cellPhone == null || this.form1datacopy.cellPhone == '' || this.form1datacopy.cellPhone == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

      },
      form1datacopy: {},
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      model3: false,
      add: false,
      tableHeight: 10,
      file: null,
      fileName: null,
      downloadUrl: Api.downloadMongoFile,
      themeList: [],
      planDatas: [],
      edit: {
        editIndex: -1,  // 当前聚焦的输入框的行数
        userName: '',
        nation: '',
        position: '',
        depName: '',
        cellPhone: '',
        accommodation: '',
        notes: '',
        sex: '',
      },
      planColumn: [
        {
          type: 'index',
          width: 80,
          align: 'center',
          title: '序号',
        },
        {
          title: '污染物产生源名称',
          minWidth: 150,
          align: 'center',
          slot: 'sourceName',
          tooltip: true,
          render: (h, params) => {
            return h('Input', {
              props: {
                type: 'text',
                value: params.row.sourceName
              },
              on: {
                'on-change': (event) => {
                  params.row.sourceName = event.target.value
                  this.form1datacopy.items[params.index] = params.row;

                }
              }
            });
          }
        },
        {
          minWidth: 120,
          title: '污染物名称',
          align: 'center',
          slot: 'pollutantName',
          tooltip: true,
          render: (h, params) => {
            return h('Input', {
              props: {
                type: 'text',
                value: params.row.pollutantName
              },
              on: {
                'on-change': (event) => {
                  params.row.pollutantName = event.target.value
                  this.form1datacopy.items[params.index] = params.row;

                }
              }
            });
          }
        },



        {
          title: '污染物排放量（千克）',
          minWidth: 130,
          align: 'center',
          slot: 'pollutantEmissions',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0,
                value: params.row.pollutantEmissions
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.pollutantEmissions = event
                  this.form1datacopy.items[params.index] = params.row;


                }
              }
            });
          }
        },
        {
          minWidth: 170,
          title: '计税依据或超标噪声综合系数',
          align: 'center',
          slot: 'zk',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0,
                value: params.row.zk
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.zk = event
                  this.form1datacopy.items[params.index] = params.row;

                }
              }
            });
          }
        },
        {
          title: '污染当量数',
          slot: 'pollutionNum',
          minWidth: 120,
          align: 'center',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0,
                value: params.row.pollutionNum
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.pollutionNum = event
                  this.form1datacopy.items[params.index] = this.currentPayableTax(params.row);
                }
              },
            })
          }
        },

        {
          minWidth: 110,
          title: '单位税额',
          align: 'center',
          slot: 'unitTax',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0,
                value: params.row.unitTax
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.unitTax = event
                  this.form1datacopy.items[params.index] = this.currentPayableTax(params.row);

                }
              }
            });
          }
        },
        {
          minWidth: 110,
          title: '本期应纳税额',
          align: 'center',
          slot: 'currentPayableTax',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                readonly:true,
                min: 0,
                value: params.row.currentPayableTax
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.currentPayableTax =event
                  this.form1datacopy.items[params.index] = params.row;

                }
              }
            });
          }
        },
        {
          minWidth: 110,
          title: '本期减免税额',
          align: 'center',
          slot: 'currentDeductionTax',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0,
                value: params.row.currentDeductionTax
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.currentDeductionTax = event
                  this.form1datacopy.items[params.index] = params.row;

                }
              }
            });
          }
        },
        {
          minWidth: 110,
          title: '本期已缴税额',
          align: 'center',
          slot: 'taxPaid',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0,
                value: params.row.taxPaid
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.taxPaid = event
                  this.form1datacopy.items[params.index] = params.row;

                }
              }
            });
          }
        },
        {
          minWidth: 130,
          title: '本期应补(退)税额',
          align: 'center',
          slot: 'taxRefundable',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0,
                value: params.row.taxRefundable
              },
              style: {
                width: '100%',
              },
              on: {
                'on-change': (event) => {
                  params.row.taxRefundable = event
                  this.form1datacopy.items[params.index] = params.row;

                }
              }
            });
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 150,
          render: (h, params) => {
            // if(params.index===this.edit.editIndex){
            //     return h('div', [
            //         h('A', {
            //             props: {
            //                 type: 'primary',
            //                 size: 'small'
            //             },
            //             style: {
            //                 fontSize: '14px'
            //             },
            //             on: {
            //                 click: () => {
            //                     this.handleSave(params.index);
            //                 }
            //             }
            //         }, '保存'),
            //         h('Divider', {
            //             props: {
            //                 type: 'vertical',
            //             }
            //         }, ''),
            //         h('A', {
            //             props: {
            //                 type: 'primary',
            //                 size: 'small'
            //             },
            //             style: {
            //                 color: 'red',
            //                 fontSize: '14px'
            //             },
            //             on: {
            //                 click: () => {
            //                     this.edit.editIndex=-1
            //                 }
            //             }
            //         }, '取消')
            //     ]);
            // }else {
            return h('div', [
              // h('A', {
              //     props: {
              //         type: 'primary',
              //         size: 'small'
              //     },
              //     style: {
              //         fontSize: '14px'
              //     },
              //     on: {
              //         click: () => {
              //             this.handleEdit(params.row, params.index);
              //         }
              //     }
              // }, '编辑'),
              // h('Divider', {
              //     props: {
              //         type: 'vertical',
              //     }
              // }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  color: 'red',
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deletePlan(params.index);
                      },
                      cancelText: '取消'
                    });

                  }
                }
              }, '删除')
            ]);
            // }
          }
        }
      ],
      planColumnView: [
        {
          type: 'index',
          width: 80,
          align: 'center',
          title: '序号',
        },
        {
          title: '污染物产生源名称',
          minWidth: 150,
          align: 'center',
          key: 'sourceName',
          tooltip: true,
        },
        {
          minWidth: 120,
          title: '污染物名称',
          align: 'center',
          key: 'pollutantName',
          tooltip: true,
        },
        {
          title: '污染物排放量（千克）',
          minWidth: 160,
          align: 'center',
          key: 'pollutantEmissions',
        },
        {
          title: '污染当量数',
          key: 'pollutionNum',
          minWidth: 120,
          align: 'center',
        },
        {
          minWidth: 170,
          title: '计税依据或超标噪声综合系数',
          align: 'center',
          key: 'zk',
        },
        {
          minWidth: 110,
          title: '单位税额',
          align: 'center',
          key: 'unitTax',
        },
        {
          minWidth: 110,
          title: '本期应纳税额',
          align: 'center',
          key: 'currentPayableTax',
        },
        {
          minWidth: 110,
          title: '本期减免税额',
          align: 'center',
          key: 'currentDeductionTax',
        },
        {
          minWidth: 110,
          title: '本期已缴税额',
          align: 'center',
          key: 'taxPaid',
        },
        {
          minWidth: 130,
          title: '本期应补(退)税额',
          align: 'center',
          key: 'taxRefundable',
        },
      ]
    }
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
    this.selectThemeList();
    this.orderTreeHead = [
      {
        id: this.currentUser.companyId,
        type: '1',
        loading: false,
        title: this.currentUser.companyName,
        expand: false,
        children: []
      }
    ]
  },
  methods: {
    formData(date){
      if (date){
        return this.formatDate(new Date(date), "yyyy-MM-dd");
      }
      return "";
    },
    formDataTwo(date1,date2){
      if (date1&&date2){
        return this.formatDate(new Date(date1), "yyyy-MM-dd") + "~" + this.formatDate(new Date(date2), "yyyy-MM-dd");
      }
      return "";
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    activityForSelectIsTrue() {
      this.activityForSelectModal = true;
    },
    querySelect() {
      this.queryMeetingSelectModal = true

    },
    queryMetting(row) {
      this.queryMeetingSelectModal = false;
      this.form1.informId = row.proposalId;
      this.form1.noticName = row.title;
    },
    calculationPollutionNum(data){
      if (data.pollutantEmissions&&data.pollutionValue){
        data.pollutionNum = data.pollutantEmissions/data.pollutionValue
        data.pollutionNum = Math.floor(data.pollutionNum * 100) / 100
        return data;
      }
      data.pollutionNum = 0;
      return data;
    },
    currentPayableTax(data){
      if (data.unitTax&&data.pollutionNum){
        data.currentPayableTax = data.unitTax * data.pollutionNum
        data.currentPayableTax = data.currentPayableTax.toFixed(7);
        return data;
      }
      data.currentPayableTax = 0;
      return data;
    },
    getActivityData(row) {
      this.form1datacopy.activityThemeId = row.programmeId;
      this.form1datacopy.programmeName = row.programmeName;
      this.form1datacopy.activityTheme = row.themeName;
      //
      this.activityForSelectModal = false;

    },
    selectThemeList() {
      let data = {
        startPage: 1,
        size: 100
      }

      let url = Api.queryProgramme;
      this.$http.get(url, {
        params: data
      }).then((res) => {
        this.themeList = res.data.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    addPlan() {
      let item = {
        sourceName:"",
        pollutantName:"",
        computMethod:"",
        emissions:0,
        measuredConcentration:0,
        pollutantEmissions:0,
        pollutionValue:0,
        pollutionNum:0,
        zk:0,
        unitTax:0,
        currentPayableTax:0,
        currentDeductionTax:0,
        taxPaid:0,
        taxRefundable:0,
      }
      this.form1datacopy.items.push(item);
    },
    addAll() {
      let _this = this;
      this.orderTreeHead = [
        {
          id: this.currentUser.companyId,
          type: '1',
          loading: true,
          title: this.currentUser.companyName,
          expand: false,
          children: []
        }
      ]
      this.$http.get(Api.meetingReceiptBaseOrgAndUser + "/" + this.currentUser.companyId).then(function (res) {
        if (res.data.status == '200') {
          _this.orderTreeHead =
              [
                {
                  id: this.currentUser.companyId,
                  type: '1',
                  loading: false,
                  title: this.currentUser.companyName,
                  expand: false,
                  children: res.data.data
                }
              ]
        }
      }, function (err) {
        this.$Message.error('请求失败');
      });
      this.model10 = true;
    },
    addSelectplanData() {
      let tree = this.$refs.auditTree.getCheckedNodes();
      this.buttonLoading10 = true;
      if (tree.length != 0) {
        tree.forEach(item => {
          if (item.type == '2') {
            let user = {
              userName: item.title,
              id: item.id,
              nation: '',
              position: '',
              depName: '',
              cellPhone: item.mobileNum,
              accommodation: '',
              notes: '',
              sex: '',
            }
            if (!this.treeListFilter[item.id]) {
              this.treeListFilter[item.id] = item.id;
              this.planDatas.push(user);
            }
          }
        })
        this.model10 = false;
      } else {
        this.$Message.warning("请先选择用户")
      }
      this.buttonLoading10 = false;

    },
    addHandleCancel() {
      this.model10 = false;
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 44;
      } else {
        this.tableHeight = this.tableHeight + 44;
      }
    },
    showData(data, flag) {
      this.buttonLoading = false;
      if (flag == 1) {
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        // this.form1datacopy.receiptDate = this.formatDate(new Date(this.form1datacopy.receiptDate), 'yyyy-MM-dd');
        // this.getFiles();
        this.model2 = true;
      } else {
        //修改页面
        this.add = false;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        // this.form1datacopy.receiptDate = this.formatDate(new Date(this.form1datacopy.receiptDate), 'yyyy-MM-dd');
        this.form1datacopy.taxPeriod = [this.form1datacopy.taxPeriodStart,this.form1datacopy.taxPeriodEnd];
        this.model1 = true;
      }
    },

    getSelectRows(rows) {
      this.deleteRows = rows;
    },

    deleteData(params) {
      let url = Api.deleteEnvTax;
      this.$http.delete(url+params.row.id).then((res) => {
        if (res.data.status == 201) {
          this.$Message.error(res.data.msg);
        } else {
          this.$Message.success("删除成功");
        }
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },

    query() {
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: sessionStorage('userId').getObject('userId').companyId

      };
      this.loading = true;

      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

      let url = Api.queryEnvTax;
      this.$http.get(url, {
        params: data
      }).then((res) => {
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    setOrgId(data) {
      this.form1datacopy.companyId = data[data.length - 1];
    },
    setOrgName(data) {
      this.form1datacopy.companyName = data;
    },

    setOrgId1(data) {
      this.form1.companyId = data[data.length - 1];
    },
    setOrgName1(data) {
      this.form1.companyName = data;
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
      this.model3 = false;
      this.planDatas = [];
    },
    isAccommodationView(data) {
      if (!data) return "";
      return data === '1' ? '是' : '否';
    },
    reset() {
      this.form1 = {}
      this.$refs.org1.resetCurrentOrg();
      this.query();
    },
    submit(name) {
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (valid) {
          _this.form1datacopy.taxPeriodStart = _this.formatDate(new Date(this.form1datacopy.taxPeriod[0]), 'yyyy-MM-dd');
          _this.form1datacopy.taxPeriodEnd = _this.formatDate(new Date(this.form1datacopy.taxPeriod[1]), 'yyyy-MM-dd');
          _this.buttonLoading = true;
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
          if (_this.add) {
            _this.form1datacopy.createUserId = userId;
            _this.form1datacopy.createOrgId = orgId;
            _this.$http.post(Api.saveEnvTax, _this.form1datacopy).then((res) => {
              if (res.data.status == 200){
                _this.$Message.success("保存成功")
                _this.model1 = false;
                _this.query();
              }else{
                _this.$Message.error("新增失败")
              }
              _this.buttonLoading = false;
            }).catch(e => {
              _this.model1 = false;
              _this.query();
              _this.$Message.error("数据获取失败")
            })
          } else {
            _this.form1datacopy.updateUserId = userId;
            _this.form1datacopy.updateOrgId = orgId;
            _this.$http.put(Api.updateEnvTax, _this.form1datacopy).then((res) => {
              if (res.data.status == 200){
                _this.$Message.success("保存成功")
                _this.model1 = false;
                _this.query();
              }else{
                _this.$Message.error("修改失败")
              }
              _this.buttonLoading = false;
            }).catch(e => {
              _this.model1 = false;
              _this.query();
              _this.$Message.error("数据获取失败")
            })
          }
        } else {
          _this.$Message.error('请填报完整!');
        }
      })
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      console.log(a);
      return a;
    },
    addInfo() {
      let _this = this;
      this.treeListFilter = {};
      this.form1datacopy = {
        companyId: _this.currentUser.companyId,
        companyName: _this.currentUser.companyName,
        twoOrgName: _this.currentUser.twoLevelOrgName,
        twoLevelOrgId: _this.currentUser.twoLevelOrgId,
        fillDate: new Date(),
        taxPeriod:[],
        items:[],
      };
      this.uploadList = [];
      this.add = true;
      this.model1 = true;
    },

    deletePlan(index) {
      this.form1datacopy.items.splice(index, 1);

    },

    downloadFiles(id) {
      this.isSpin = true;
      this.$http.get(Api.downloadEnvTax+id, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "环境保护税统计表(" + this.formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.isSpin = false;
      })
    },
    /* downloadFile(guideId, file) {
         let url = this.fileUrl + '/file/' + file.id;
         this.$http.get(url, {
             responseType: 'blob'      //告诉服务器我们需要的响应格式
         }).then((res) => {
             const aLink = document.createElement("a");
             let blob = new Blob([res.data], {
                 type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
             });
             aLink.href = URL.createObjectURL(blob)
             aLink.download = file.fileName //标题
             aLink.click()
             document.body.appendChild(aLink)
         })
     },
     remove1(id) {
         console.log(id)
         let url = this.fileUrl + '/file/' + id;
         this.$http.delete(url).then((res) => {
             this.getFiles()
         })
     },
     beforeUpload(file) {
         let formData = new FormData();
         formData.append("files", file); // 文件对象
         let url = this.fileUrl + '/' + this.form1datacopy.depId + '/files/receipt'
         this.$http.post(url, formData).then((res) => {
             if (res.data.result == "success") {
                 this.$Message.info("文件上传成功")
                 this.getFiles();
             }
         })
         return false
     },
     getFiles() {
         let url = this.fileUrl + '/' + this.form1datacopy.depId + '/files/receipt'
         this.$http.get(url).then((res) => {
             if (res.data.result == "success") {
                 this.uploadList = res.data.data
             }
         })
     },*/
    openSelect() {
      this.standardSelectModal = true
    },
    selectReceipt(row) {
      this.standardSelectModal = false;
      this.form1datacopy.informId = row.proposalId;
      this.form1datacopy.informName = row.title;
    },
  },
  watch: {
    "model3": function (qw, er) {
      if (qw && this.model3) {
        setTimeout(() => {
          this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        this.$refs.trainOrg.resetCurrentOrg();

      }
    },
    "switchFlag": function (qw, er) {
      if (this.switchFlag) {
        setTimeout(() => {
          this.$refs.org1.setCurrentOrg();
          this.$refs.org2.setCurrentOrg();

        }, 100)
      } else {
        setTimeout(() => {
          this.$refs.org1.setCurrentOrg();
          this.$refs.org2.setCurrentOrg();

        }, 100)

      }
    },

  },
}
</script>
<style lang='css' scoped>
@import '../../../index.css';

.tableClass {
}

.tableClass >>> .ivu-table td {
  vertical-align: middle;
}

.tableClass >>> .ivu-table th {
  vertical-align: middle;
}

.tableClass >>> .ivu-input-suffix i {
  font-size: 16px;
  line-height: 50px;
  color: #808695;
}

.tableClass >>> .ivu-input {
  border-radius: 0px;
  vertical-align: middle;
  height: 100%;
}

.tableClass >>> textarea.ivu-input {
  height: 100%;
  vertical-align: middle;
}

.tableClass >>> ivu-date-picker {
  height: 100%;
  vertical-align: middle;
}

.tableClass >>> .ivu-table-cell {
  padding-left: 0px;
  padding-right: 0px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  box-sizing: border-box;
  height: 100%;
  /*flex 布局*/
  display: flex;
  /*实现垂直居中*/
  align-items: center;
  /*实现水平居中*/
  justify-content: center;
  text-align: justify;
}

.tableClass >>> .ivu-date-picker {
  height: 100%;
}

.tableClass >>> .ivu-date-picker {
  height: 100%;
}

.tableClass >>> .ivu-input-wrapper {
  height: 100%;
}

.tableClass >>> .ivu-date-picker-rel {
  height: 100%;
}

.tableClass >>> .ivu-input-icon {
  line-height: 50px;
}

.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
